package com.ins1st.modules.blog.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ins1st.core.R;
import com.ins1st.modules.blog.entity.Article;
import com.ins1st.modules.blog.service.ArticleService;
import com.ins1st.util.Jackson;
import com.ins1st.util.QueryUtil;
import com.ins1st.util.ResponseUtils;
import com.ins1st.util.ShiroUtil;

@Controller
@RequestMapping("/blog/article")
public class ArticleAction {

	private static final String PREFIX = "modules/blog/";

	@Autowired
	private ArticleService articleService;

	/**
	 * 主页
	 */
	@RequestMapping("index")
	public String index() {
		return PREFIX + "article_index.html";
	}

	/**
	 * 查询集合
	 */
	@RequestMapping("list")
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		QueryWrapper<Article> query = new QueryWrapper<>();
		IPage page = QueryUtil.getPage(request);
		articleService.page(page, query);
		Map<String, Object> data = R.return4Page(page);
		
		String json = Jackson.me().without(Article.class, "content").toJson(data);
		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 添加页
	 */
	@RequestMapping("add")
	public String add(Model model) {
		return PREFIX + "article_form.html";
	}

	/**
	 * 保存
	 */
	@RequestMapping("save")
	@ResponseBody
	public Object save(Article article) {
		Long id = article.getId();
		boolean save = true;
		if(id == null) { //新增
			article.setAuthor(ShiroUtil.getUser().getId());
			save = articleService.saveOrUpdate(article);
		} else {
			Article orgArticle = articleService.getById(id);
			orgArticle.setTitle(article.getTitle());
			orgArticle.setContent(article.getContent());
			orgArticle.setAuthor(ShiroUtil.getUser().getId());
			save = articleService.saveOrUpdate(orgArticle);
		}
		
		if (save) {
			return R.success("保存成功");
		}
		return R.error("保存失败");
	}

	/**
	 * 修改页
	 */
	@RequestMapping("get/{id}")
	public String edit(@PathVariable Long id, Model model) {
		Article article = articleService.getById(id);
		model.addAttribute("article", article);
		return PREFIX + "article_form.html";
	}

	/**
	 * 删除
	 */
	@RequestMapping("del/{id}")
	@ResponseBody
	public Object del(@PathVariable Long id) {
		boolean del = articleService.removeById(id);
		if (del) {
			return R.success("删除成功");
		}
		return R.error("删除失败");
	}

}
